/*
  EOMono
  Copyright 2007, Adam Tauno Williams (Whitemice Consulting)
  License: LGPLv2  < http://www.gnu.org/licenses/lgpl-2.1.html >
 */
using System;
using System.Text;

namespace Whitemice.EOMono
{
  [EOCommandAttribute("SQLNew", 1, "Insert the provided record")]
  public class EOSQLNewCommand : EOSQLCommand, IEOCommand
  {
    protected IEORecord  record = null;
    
    public EOSQLNewCommand(IEOConnection _connection, string _entity) :
      base(_connection, _entity)
    {
    } // end ctor
    
    [EOArguementAttribute("record", "")]
    public IEORecord Record
    {
      set { record = value; }
      get { return record; }
    } // end Record
    
    protected override void Execute()
    {
      bool        first;
      StringBuilder    sql;
      
      if (Record == null)
        throw new Exception("New command with no record");
        
      if (Record.Entity.ReadOnly)
        throw new Exception("New command on read-only entity.");
      
      if (!(Record.IsInsertComplete))
        throw new Exception("New command with incomplete record");
        
      if (!(Record.IsNew))
        throw new Exception("New command with pre-existing record");

      first = true;
      sql = new StringBuilder();
      foreach(string field in Record.FieldNames)
      {
        if (first)
        {
          sql.AppendFormat("INSERT INTO {0} ({1}",
                  Record.Entity.InternalName,
                  field);
          first = false;
        } else
          {
            sql.AppendFormat(", {0}",field);
          }
      } // end foreach-field-name
      sql.Append(") VALUES (");
      first = true;
      foreach(string field in Record.FieldNames)
      {
        if (first)
        {
          sql.Append(Record.SQLValue(field));
          first = false;
        } else
          {
            sql.AppendFormat(", {0}", Record.SQLValue(field));
          }
      } // end foreach-field-name
      sql.Append(")");
      EOManager.Log.DebugFormat("SQL:{0}", sql.ToString());
      command.CommandText = sql.ToString();
      command.ExecuteNonQuery();
      Record.Saved();
      if (Record.Entity.MagicPrimaryKey)
      {
        object result = connection.LastSerialId(this);
        if (result == null)
        {
          results = null;
        } else
          {
            results = connection.Run(string.Format("{0}:SQLFetch", Record.Entity.Name),
                                     "qualifier", PrimaryKeyQualifier(Record, result)); 
          }
      } else 
        {
          results = connection.Run(string.Format("{0}:SQLFetch", Record.Entity.Name),
                                   "qualifier", PrimaryKeyQualifier(Record)); 
        }
      // copy fields from result of fetch into provided record
      if (results.Count > 0)
      {
        foreach (string name in results[0].FieldNames)
          if (results[0][name].HasValue)
            Record[name].Value = results[0][name].Value;
      } // end if-results
    } // end Execute
  } // end class
}